//
//  shopDetailVC.m
//  WuyouTang
//
//  Created by IOS1 on 2019/7/5.
//  Copyright © 2019 cat. All rights reserved.
//

#import "ShopDetailVC.h"
#import "ShopCell.h"
#import "AddGoodsVC.h"
#import "GoodsDetailViewController.h"
#import "CommodityDetailVC.h"
#import "StoreInfoView.h"
#import "ShopInfoVC.h"
#import "JCHATConversationViewController.h"
#import "OutsideGoodsDetailVC.h"
#import "PlatformCell.h"
@interface ShopDetailVC ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    int page;
    NSMutableArray *infoArray;
    UIImageView *bigImgView;
    UIImageView *iconImgV;
    UILabel *nameL;
    UILabel *contentL;
    UILabel *numL;
    UILabel *platformNumL;

    UIView *headerView;
    
    UIButton *saleBtn;
    UIButton *platfromBtn;
    UIButton *allreturnBtn;
    NSDictionary *shopInfo;
    NSString *numsStr;
    StoreInfoView *_infoView;
    UIButton *customerBtn;
    
    NSArray *titleArr;
    UILabel *lineLb;
    
    BOOL isPlatform;
    UIView *noDataView;

}
@property (nonatomic,strong) UICollectionView *shopCollectView;

@end

@implementation ShopDetailVC
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}
    

- (void)addBtnClick{
    AddGoodsVC *vc = [[AddGoodsVC alloc]init];
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    self.titleL.text = [common shop_system_name];
    infoArray = [NSMutableArray array];
    page = 1;
    [self creatUI];
//    [self requestData];
    if (titleArr.count > 1) {
        [self requestData];
    }else{
        [self getPlatformGoods];
    }
    [self createNoDataView];
}
- (void)creatUI{
    headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 180)];
    headerView.backgroundColor = [UIColor whiteColor];

    iconImgV = [[UIImageView alloc]initWithFrame:CGRectMake(15, 15, 50, 50)];
    iconImgV.layer.cornerRadius = 25;
    iconImgV.layer.masksToBounds = YES;
    iconImgV.contentMode = UIViewContentModeScaleAspectFill;
    iconImgV.clipsToBounds = YES;
    iconImgV.backgroundColor = Normal_Color;
    [headerView addSubview:iconImgV];
    
    
    nameL = [[UILabel alloc]init];
    nameL.textColor = [UIColor blackColor];
    nameL.font = [UIFont boldSystemFontOfSize:14];
    [headerView addSubview:nameL];
    [nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconImgV).offset(10);
        make.left.equalTo(iconImgV.mas_right).offset(15);
    }];

    UIButton *shopTap = [UIButton buttonWithType:0];
    [shopTap addTarget:self action:@selector(shopTapClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:shopTap];
    [shopTap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(nameL);
    }];
    
    UIImageView *rightImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"shop_right"]];
    [headerView addSubview:rightImg];
    [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameL.mas_right).offset(5);
        make.height.width.mas_equalTo(16);
        make.centerY.equalTo(nameL.mas_centerY);
    }];
    
    customerBtn = [UIButton buttonWithType:0];
    [customerBtn setImage:[UIImage imageNamed:@"shophome_客服"] forState:0];
    [customerBtn addTarget:self action:@selector(customerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:customerBtn];
    [customerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView.mas_right).offset(-15);
        make.height.width.mas_equalTo(20);
        make.centerY.equalTo(nameL.mas_centerY);
    }];
    if ([[Config getOwnID] isEqual:_toUserID]) {
        customerBtn.hidden = YES;
    }
    
    _infoView = [[StoreInfoView alloc]initWithFrame:CGRectMake(15, iconImgV.bottom +10, _window_width-30, 64)];
    _infoView.layer.cornerRadius = 5;
    _infoView.layer.masksToBounds = YES;
    [headerView addSubview:_infoView];

    UIView *numView = [[UIView alloc]init];
    numView.backgroundColor =RGB_COLOR(@"#f5f5f5", 1);
    numView.frame = CGRectMake(0, headerView.height-30, _window_width, 30);
    [headerView addSubview:numView];
    if ([_toUserID isEqual:@"1"]) {
        titleArr = @[YZMsg(@"平台自营")];

    }else{
        titleArr = @[YZMsg(@"在售商品"),YZMsg(@"平台自营")];
    }
    for (int i = 0; i < titleArr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(iconImgV.left +60*i+40*i, numView.height/2-10, 60, 20);
        [btn setTitle:titleArr[i] forState:0];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        [btn setTitleColor:RGB_COLOR(@"#969696", 1) forState:0];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(goodsListBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 20000+i;
        [numView addSubview:btn];
        
        UILabel *lb = [[UILabel alloc]init];
        lb.frame = CGRectMake(btn.right, btn.top, 30, 20);
        lb.textColor = RGB_COLOR(@"#969696", 1);
        lb.font = [UIFont systemFontOfSize:12];
        [numView addSubview:lb];
        
        if (titleArr.count > 1) {
            if ( i == 0) {
                saleBtn = btn;
                numL = lb;
                saleBtn.selected = YES;

            }else{
                platfromBtn  =btn;
                platformNumL = lb;
            }
        }else{
            platfromBtn  =btn;
            platformNumL = lb;
            platfromBtn.selected = YES;
        }

    }
    lineLb = [[UILabel alloc]init];
    if (titleArr.count > 1) {
        lineLb.frame = CGRectMake(0, saleBtn.bottom, 20, 2);
        lineLb.centerX = saleBtn.centerX;
    }else{
        lineLb.frame = CGRectMake(0, platfromBtn.bottom, 20, 2);
        lineLb.centerX = platfromBtn.centerX;

    }
    lineLb.backgroundColor = Pink_Cor;
    lineLb.layer.cornerRadius = 1;
    lineLb.layer.masksToBounds = YES;
    [numView addSubview:lineLb];
    [self.view addSubview:self.shopCollectView];
    [self.view sendSubviewToBack:_shopCollectView];

}
-(void)goodsListBtnClick:(UIButton *)sender
{
    if (titleArr.count > 1) {
        page = 1;
        if (sender.tag == 20000) {
            //在售商品
            saleBtn.selected = YES;
            platfromBtn.selected = NO;
            lineLb.centerX = saleBtn.centerX;
            isPlatform = NO;
            [self requestData];
        }else{
            //平台自营
            saleBtn.selected = NO;
            platfromBtn.selected = YES;
            lineLb.centerX = platfromBtn.centerX;
            isPlatform = YES;
            [self getPlatformGoods];
        }
    }else{
        page = 1;
        platfromBtn.selected = YES;
        lineLb.centerX = platfromBtn.centerX;
        isPlatform = YES;
        [self getPlatformGoods];
    }
}
-(void)customerBtnClick{
    if ([_toUserID isEqual:@"1"]) {
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"请到个性设置-关于我们中联系客服") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [sureAction setValue:Normal_Color forKey:@"_titleTextColor"];
        [alertControl addAction:sureAction];
        [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:alertControl animated:YES completion:nil];
    }else{
        NSDictionary *userDic = @{
            @"id":strFormat([shopInfo valueForKey:@"uid"]),
            @"user_nickname":strFormat([shopInfo valueForKey:@"user_nickname"]),
            @"avatar":strFormat([shopInfo valueForKey:@"avatar"]),
        };
        [[YBMessageManager shareManager] chatWithUser:userDic];
    }

}
-(void)shopTapClick{
    ShopInfoVC *shop = [[ShopInfoVC alloc]init];
    shop.shopInfoDic =shopInfo;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:shop animated:YES];
}
-(void)createNoDataView{
    noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 200, _window_width, 150)];
    noDataView.hidden = YES;
    noDataView.backgroundColor = [UIColor clearColor];
    [_shopCollectView addSubview:noDataView];
    
    UIImageView *noImg = [[UIImageView alloc]init];
    noImg.frame = CGRectMake(_window_width/2-40, 10, 81, 51);
    noImg.image = [UIImage imageNamed:@"shop_无数据"];
    [noDataView addSubview:noImg];
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, noImg.bottom+10, _window_width, 20)];
    label2.font = [UIFont systemFontOfSize:13];
    label2.text = YZMsg(@"你还没有相关商品");
    label2.textAlignment = NSTextAlignmentCenter;
    label2.textColor = RGB_COLOR(@"#969696", 1);
    [noDataView addSubview:label2];

    noDataView.hidden = YES;
}

- (UICollectionView *)shopCollectView{
    if (!_shopCollectView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
        flow.minimumLineSpacing = 7;
        flow.minimumInteritemSpacing = 7;
        flow.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7);
        flow.headerReferenceSize = CGSizeMake(_window_width, 180);
        _shopCollectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,64+statusbarHeight, _window_width, _window_height-64-statusbarHeight) collectionViewLayout:flow];
        [_shopCollectView registerNib:[UINib nibWithNibName:@"shopCell" bundle:nil] forCellWithReuseIdentifier:@"shopCELL"];
        [_shopCollectView registerNib:[UINib nibWithNibName:@"PlatformCell" bundle:nil] forCellWithReuseIdentifier:@"PlatformCELL"];

        [_shopCollectView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"storeHeaderV"];
        _shopCollectView.delegate =self;
        _shopCollectView.dataSource = self;
        _shopCollectView.backgroundColor = RGB_COLOR(@"#f5f5f5", 1);
        _shopCollectView.mj_footer  = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            page ++;
//            [self requestData];
            if (titleArr.count > 1) {
                if (saleBtn.selected == YES) {
                    [self requestData];

                }else{
                    [self getPlatformGoods];
                }
            }else{
                [self getPlatformGoods];
            }

        }];
        
        _shopCollectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            page = 1;
            if (titleArr.count > 1) {
                if (saleBtn.selected == YES) {
                    [self requestData];

                }else{
                    [self getPlatformGoods];
                }
            }else{
                [self getPlatformGoods];
            }

//            [self requestData];
        }];
        
        if (@available(iOS 11.0, *)) {
            _shopCollectView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _shopCollectView;
}

-(void)getPlatformGoods{
    [WYNetworking postWithUrl:@"Shop.getOnsalePlatformGoods" Dic:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"p":@(page),@"touid":_toUserID} Suc:^(int code, id info, NSString *msg) {
        [_shopCollectView.mj_header endRefreshing];
        [_shopCollectView.mj_footer endRefreshing];
        if (code ==0) {
            NSDictionary *dic = [info firstObject];
            
            NSArray *list = [dic valueForKey:@"list"];
            shopInfo = [dic valueForKey:@"shop_info"];
            numsStr = minstr([shopInfo valueForKey:@"goods_nums"]);
            numL.text = [NSString stringWithFormat:YZMsg(@"%@件"),numsStr];
            CommodityDetailModel *model = [[CommodityDetailModel alloc]init];
            model.shop_sale_nums = minstr([shopInfo valueForKey:@"sale_nums"]);
            model.quality_points =minstr([shopInfo valueForKey:@"quality_points"]);
            model.service_points =minstr([shopInfo valueForKey:@"service_points"]);
            model.express_points =minstr([shopInfo valueForKey:@"express_points"]);
            model.other_sale_nums = minstr([shopInfo valueForKey:@"platform_goods_nums"]);
            platformNumL.text =[NSString stringWithFormat:YZMsg(@"%@件"),model.other_sale_nums];

            [_infoView setStoreModels:model];
            if (!iconImgV.image) {
                [iconImgV sd_setImageWithURL:[NSURL URLWithString:minstr([shopInfo valueForKey:@"avatar"])]];
                nameL.text = minstr([shopInfo valueForKey:@"name"]);
            }
            if (page == 1) {
                [infoArray removeAllObjects];
            }
            [infoArray addObjectsFromArray:list];
            if (infoArray.count < 1) {
                noDataView.hidden = NO;
//                [PublicView showImgNoData:_shopCollectView name:@"shop_无数据" text:YZMsg(@"没有相关商品")];
                [self.shopCollectView reloadData];
                return ;
            }else{
                noDataView.hidden = YES;
//                [PublicView hiddenImgNoData:_shopCollectView];
            }
        }
        [_shopCollectView reloadData];

        } Fail:^(id fail) {
            [_shopCollectView.mj_header endRefreshing];
            [_shopCollectView.mj_footer endRefreshing];

     }];

}

- (void)requestData{
    NSString *url = [purl stringByAppendingFormat:@"?service=Shop.GetShop"];
    
    [WYNetworking postWithUrl:@"Shop.GetShop" Dic:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"p":@(page),@"touid":_toUserID} Suc:^(int code, id info, NSString *msg) {
        [_shopCollectView.mj_header endRefreshing];
        [_shopCollectView.mj_footer endRefreshing];
        if (code ==0) {
            NSDictionary *dic = [info firstObject];
            
            NSArray *list = [dic valueForKey:@"list"];
            shopInfo = [dic valueForKey:@"shop_info"];
            numsStr = minstr([shopInfo valueForKey:@"goods_nums"]);
            numL.text = [NSString stringWithFormat:YZMsg(@"%@件"),numsStr];
            CommodityDetailModel *model = [[CommodityDetailModel alloc]init];
            model.shop_sale_nums = minstr([shopInfo valueForKey:@"sale_nums"]);
            model.quality_points =minstr([shopInfo valueForKey:@"quality_points"]);
            model.service_points =minstr([shopInfo valueForKey:@"service_points"]);
            model.express_points =minstr([shopInfo valueForKey:@"express_points"]);
            model.other_sale_nums = minstr([shopInfo valueForKey:@"platform_goods_nums"]);
            platformNumL.text =[NSString stringWithFormat:YZMsg(@"%@件"),model.other_sale_nums];

            [_infoView setStoreModels:model];
            if (!iconImgV.image) {
                [iconImgV sd_setImageWithURL:[NSURL URLWithString:minstr([shopInfo valueForKey:@"avatar"])]];
                nameL.text = minstr([shopInfo valueForKey:@"name"]);
            }
            if (page == 1) {
                [infoArray removeAllObjects];
            }
            [infoArray addObjectsFromArray:list];
            if (infoArray.count < 1) {
                noDataView.hidden = NO;

//                [PublicView showImgNoData:_shopCollectView name:@"shop_无数据" text:YZMsg(@"没有相关商品")];
                [self.shopCollectView reloadData];
                return ;
            }else{
                noDataView.hidden = YES;

//                [PublicView hiddenImgNoData:_shopCollectView];
            }

        }
        [_shopCollectView reloadData];

        } Fail:^(id fail) {
            [_shopCollectView.mj_header endRefreshing];
            [_shopCollectView.mj_footer endRefreshing];

     }];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return infoArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (isPlatform && [_toUserID isEqual:[Config getOwnID]]) {
        PlatformCell *cell = (PlatformCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"PlatformCELL" forIndexPath:indexPath];
        NSDictionary *subDic = infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        cell.commissionLb.text = [NSString stringWithFormat:YZMsg(@"佣 ¥%@"),minstr([subDic valueForKey:@"commission"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:YZMsg(@"已售%@件"),minstr([subDic valueForKey:@"sale_nums"])];
        }
        
        return cell;

    }else{
        ShopCell *cell = (ShopCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopCELL" forIndexPath:indexPath];
        NSDictionary *subDic = infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:YZMsg(@"已售%@件"),minstr([subDic valueForKey:@"sale_nums"])];
        }
        
        return cell;

    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (isPlatform && ![_toUserID isEqual:@"1"]) {
        return  CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75+30);

    }else{
      return  CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"storeHeaderV" forIndexPath:indexPath];
        
        header.backgroundColor = [UIColor whiteColor];
        [header addSubview:headerView];
        return header;
    }else{
        return nil;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *subDic = infoArray[indexPath.row];
    
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code ==0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid= _toUserID;
                if ([[Config getOwnID] isEqual:_toUserID] && !isPlatform) {
                    detail.fromWhere = @"seller";
                }
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.backTags = @"shop";
                detail.liveUid= _toUserID;
                if ([[Config getOwnID] isEqual:_toUserID] && !isPlatform) {
                    detail.fromWhere = @"seller";
                }

                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }

        }else{
            [MBProgressHUD showError:msg];

        }
    }];

    
}

@end
